package com.hpin.mlxteacher.my;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.hpin.mlxteacher.R;
import com.hpin.mlxteacher.adapter.SchoolClassAdapter;
import com.hpin.mlxteacher.base.BaseActivity;
import com.hpin.mlxteacher.bean.SchoolClassReq;
import com.hpin.mlxteacher.swipe.SwipeMenu;
import com.hpin.mlxteacher.swipe.SwipeMenuCreator;
import com.hpin.mlxteacher.swipe.SwipeMenuItem;
import com.hpin.mlxteacher.swipe.SwipeMenuListView;
import com.hpin.mlxteacher.utils.Constant;
import com.hpin.mlxteacher.utils.DensityUtil;
import com.hpin.mlxteacher.utils.HttpUtil;
import com.hpin.mlxteacher.zxing.CaptureActivity;

import java.util.ArrayList;
import java.util.List;

/**
 * 学校班级页面
 * Created by Administrator on 2015/11/11.
 */
public class SchoolClassActivity extends BaseActivity implements View.OnClickListener {

    private ImageView iv_left;
    private ImageView iv_right;
    private TextView tv_title;
    private Intent mIntent;
    private SwipeMenuListView lv_safe_area;
    private SchoolClassAdapter schoolClassAdapter;
    private List<SchoolClassReq.MyClassesList> temList;
    public static final int ZXING_CODE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_school_class);
        temList = new ArrayList<SchoolClassReq.MyClassesList>();
        init();
        myClasses();
    }

    private void myClasses() {

        JSONObject j = new JSONObject();
        j.put("token", sp.getString(Constant.token, ""));

        HttpUtil.setPostRequest("请稍后...", this, Constant.WEB_ROOT + Constant.MYCLASSES, j.toJSONString(),
                getClass().getName(), new HttpUtil.SuccessListener() {
                    @Override
                    public void setOnSuccessListener(String str) {
                        try {
                            SchoolClassReq schoolClassReq = JSONObject.parseObject(str, SchoolClassReq.class);

                            if (schoolClassReq.code == Constant.SUCCESS) {

                                if (schoolClassReq.data != null) {

                                    temList = schoolClassReq.data;
                                    schoolClassAdapter.setData(temList);
                                    schoolClassAdapter.notifyDataSetChanged();

                                } else {
                                    showToast("获取失败!");
                                }
                            } else {
                                showToast(Constant.showErrorMsg(schoolClassReq.code, SchoolClassActivity.this));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }, null);

    }

    private void init() {
        iv_left = (ImageView) findViewById(R.id.iv_left);
        iv_right = (ImageView) findViewById(R.id.iv_right);
        tv_title = (TextView) findViewById(R.id.tv_title);
        lv_safe_area = (SwipeMenuListView) findViewById(R.id.lv_safe_area);
        tv_title.setText(getResources().getString(R.string.school_class));

        iv_left.setOnClickListener(this);
        iv_right.setOnClickListener(this);
        schoolClassAdapter = new SchoolClassAdapter(this, temList);
        lv_safe_area.setAdapter(schoolClassAdapter);
        lv_safe_area.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                //获取到选中的宝宝的id
//                String childIds = temList.get(position).id;

//                SharedPreferences.Editor edit = sp.edit();
//                edit.putString(Constant.childIds, childIds);
//                edit.apply();
            }

        });
        //滑动删除
        SwipeMenuCreator creator = new SwipeMenuCreator() {
            @Override
            public void create(SwipeMenu menu) {

                SwipeMenuItem deleteItem = new SwipeMenuItem(getApplicationContext());

                deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9, 0x3F, 0x25)));

                deleteItem.setWidth(DensityUtil.dip2px(SchoolClassActivity.this, 50));

//                deleteItem.setIcon(R.drawable.ic_delete);

                deleteItem.setTitle("删除");

                deleteItem.setTitleColor(getResources().getColor(R.color.white));

                deleteItem.setTitleSize(18);

                menu.addMenuItem(deleteItem);

            }
        };

        lv_safe_area.setMenuCreator(creator);

        lv_safe_area.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(final int position, SwipeMenu menu, int index) {
                switch (index) {
                    case 0:

                        new AlertDialog.Builder(SchoolClassActivity.this).setMessage("删除该班级")
                                .setNegativeButton("取消", null).setPositiveButton("删除", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                dialog.dismiss();

                                if (temList != null && temList.get(position) != null) {
                                    delArea(temList.get(position).id);
                                }

                            }
                        }).show();

                        break;
                }
                return false;
            }
        });
    }

    /**
     * 删除班级
     *
     * @param classId
     */
    private void delArea(final String classId) {

        JSONObject j = new JSONObject();
        j.put("token", sp.getString(Constant.token, ""));
        j.put("classId", classId);

        HttpUtil.setPostRequest("请稍后...", this, Constant.WEB_ROOT + Constant.TEACHERUNBINDCLASS, j.toJSONString(),
                getClass().getName(), new HttpUtil.SuccessListener() {
                    @Override
                    public void setOnSuccessListener(String str) {
                        try {

                            org.json.JSONObject result = new org.json.JSONObject(str);

                            if (result.getInt("code") == Constant.SUCCESS) {
                                showToast("删除成功!");

                                if (sp.getString(Constant.classId, "").equals(classId)) {
                                    //如果当前选中的班级被删除了,则把当前的classid清空
                                    SharedPreferences.Editor edit = sp.edit();
                                    edit.putString(Constant.classId, "");
                                    edit.apply();
                                }

                                myClasses();
                            } else {

                                showToast(Constant.showErrorMsg(result.getInt("code"), SchoolClassActivity.this));

                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            showToast(Constant.NODATA);
                        }
                    }
                }, null);
    }

    @Override
    public void widgetClick(View v) {
        switch (v.getId()) {
            case R.id.iv_left:
                finish();
                break;
            case R.id.iv_right:
                mIntent = new Intent(this, CaptureActivity.class);
                startActivityForResult(mIntent, ZXING_CODE);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case ZXING_CODE:

                if (data == null)
                    return;
                String zxingCode = data.getStringExtra("zxing_code");

                try {

                    org.json.JSONObject resutl = new org.json.JSONObject(zxingCode);

                    teacherBindClass(resutl.getString("classCode"));

                } catch (Exception e) {
                    e.printStackTrace();
                    showToast("无法解析出班级信息");
                }
                break;
        }

    }

    /**
     * 绑定孩子班级
     *
     * @param classCode 班级code
     */
    private void teacherBindClass(String classCode) {

        JSONObject j = new JSONObject();
        j.put("token", sp.getString(Constant.token, ""));
        j.put("classCode", classCode);

        HttpUtil.setPostRequest("加载中...", this, Constant.WEB_ROOT + Constant.TEACHERBINDCLASS, j.toJSONString(),
                getClass().getName(), new HttpUtil.SuccessListener() {
                    @Override
                    public void setOnSuccessListener(String str) {

                        try {

                            org.json.JSONObject result = new org.json.JSONObject(str);

                            if (result.getInt("code") == Constant.SUCCESS) {
                                if (temList != null) {
                                    myClasses();
                                    showToast("绑定班级成功!");
                                } else
                                    showToast("没有新数据");
                            } else
                                showToast(Constant.showErrorMsg(result.getInt("code"), SchoolClassActivity.this));

                        } catch (Exception e) {
                            e.printStackTrace();
                            showToast(Constant.NODATA);
                        }

                    }
                }, null);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        mApplication.cancelPendingRequests(getClass().getName());

    }
}
